package sharping.appilog.fragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONArray;

import sharping.appilog.R;
import sharping.appilog.SearchPage;
import sharping.appilog.app;
import sharping.appilog.Adapter.RTimeLineAdapter;
import sharping.appilog.DataTree.TimeLineData;
import sharping.appilog.Logic.ScreenSize;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.android.volley.Request.Method;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;

public class Fragment_Search extends Fragment {

	TextView divider;
	ListView list;
	ImageView search_remove_text;
	ArrayList<String> list_empty = new ArrayList<String>();
	LayoutInflater inflater;
	EditText searchQuery;
	ArrayList<TimeLineData> list_data;
	boolean isRemoveClick = false;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		this.inflater = inflater;
		
		View v = inflater.inflate(R.layout.fragment_search, null);

		divider = new TextView(getActivity());
		ListView.LayoutParams params = new ListView.LayoutParams(
				LayoutParams.MATCH_PARENT, ScreenSize.DPtoPX(getActivity(), 4));
		divider.setLayoutParams(params);

		list = (ListView) v.findViewById(R.id.fragment_search_list);
		// list.setDividerHeight(ScreenSize.DPtoPX(getActivity(), 4));
		// list.setDivider(new
		// ColorDrawable().setColor(android.R.color.transparent));
		// list.setVerticalScrollBarEnabled(false);

		list.addHeaderView(divider, null, false);
		list.addFooterView(divider, null, false);

		// list.setSelector(getResources().getDrawable(android.R.color.transparent));

		searchQuery = (EditText) v.findViewById(R.id.fragment_search_query);
		
		View emptyView = inflater.inflate(R.layout.empty_list, null);
		list.setEmptyView(emptyView);
		
		search_remove_text = (ImageView) v.findViewById(R.id.fragment_search_remove_text);
		
		// return inflater.inflate(R.layout.fragment_search, null);
		return v;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);

		// list = (ListView)
		// getActivity().findViewById(R.id.fragment_search_list);
		// list.setDivider(null);
		// list.setDividerHeight(ScreenSize.DPtoPX(getActivity(), 4));
		// list.setVerticalScrollBarEnabled(false);
		//
		// list.addHeaderView(divider, null, false);
		// list.addFooterView(divider, null, false);
		//
		// list.setSelector(getResources()
		// .getDrawable(android.R.color.transparent));
		search_remove_text.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (isRemoveClick) {
					searchQuery.setText("");					
				}
			}
		});
		
		searchQuery.addTextChangedListener(new TextWatcher() {
			
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				if (s.length() != 0) {
					isRemoveClick = true;
					search_remove_text.setImageResource(R.drawable.ic_text_remove);
				} else {
					isRemoveClick = false;
					search_remove_text.setImageResource(getResources().getColor(android.R.color.transparent));
				}
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				
			}
		});

		list.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				Intent intent = new Intent(getActivity(), SearchPage.class);
				intent.putExtra(
						"Query",
						getResources().getStringArray(R.array.list_category)[arg2 - 1]);
				getActivity().startActivity(intent);
			}
		});

		// inflater = LayoutInflater.from(getActivity());
		// searchQuery = (EditText) getActivity().findViewById(
		// R.id.fragment_search_query);
		searchQuery.setOnEditorActionListener(new OnEditorActionListener() {

			@Override
			public boolean onEditorAction(TextView v, int actionId,
					KeyEvent event) {

				if (actionId == EditorInfo.IME_ACTION_SEARCH) {
					if (searchQuery.getText().toString().length() > 0) {
						Intent intent = new Intent(getActivity(), SearchPage.class);
						intent.putExtra("Query", searchQuery.getText().toString());
						
						InputMethodManager imm = (InputMethodManager) getActivity()
								.getSystemService(Context.INPUT_METHOD_SERVICE);
						imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
						getActivity().startActivity(intent);						
					}
				}

				return false;
			}
		});

//		View v = inflater.inflate(R.layout.list_empty, null);
//		list.setEmptyView(v);

		list.setAdapter(new defaultAdapter());
		// list.invalidate();
	}

	private Listener<String> onSearch = new Listener<String>() {
		@Override
		public void onResponse(String result) {
			try {
				JSONArray entry = new JSONArray(result);
				list_data = new ArrayList<TimeLineData>();

				for (int i = 0; i < entry.length(); i++) {

					list_data.add(new TimeLineData(entry.getJSONObject(i)
							.getString("CTimeLineIndex"), entry
							.getJSONObject(i).getString("CBizId"), entry
							.getJSONObject(i).getString("CUserId"), entry
							.getJSONObject(i).getString("CTimeLineContents"),
							entry.getJSONObject(i).getString("CTimeLineDate"),
							entry.getJSONObject(i).getString("CBizName"), entry
									.getJSONObject(i).getString(
											"TimeLineImgURL"), entry
									.getJSONObject(i).getString("CUserName"),
							entry.getJSONObject(i).getString("CUserImgURL"),
							entry.getJSONObject(i).getString("CLikeCount"),
							entry.getJSONObject(i).getString("CReplyCount"),
							entry.getJSONObject(i).getString("CBizCategory"),
							entry.getJSONObject(i).getString("isLike")));

				}

				list.setAdapter(new RTimeLineAdapter(getActivity(), inflater,
						list_data, 0));
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
	};

	private ErrorListener error = new ErrorListener() {

		@Override
		public void onErrorResponse(VolleyError err) {
			// TODO Auto-generated method stub

		}
	};

	private StringRequest onSearchList = new StringRequest(Method.POST,
			app.HOST_URL + "rmobile/select_search_timeline.php", onSearch,
			error) {
		protected java.util.Map<String, String> getParams()
				throws com.android.volley.AuthFailureError {

			Map<String, String> params = new HashMap<String, String>();
			params.put("SearchQuery", searchQuery.getText().toString());

			return params;
		};
	};

	private class defaultAdapter extends BaseAdapter {

		String[] default_data = getActivity().getResources().getStringArray(
				R.array.list_category);
		int[] defalt_img = { R.drawable.ic_categori11_1,
				R.drawable.ic_categori1_1, R.drawable.ic_categori2_1,
				R.drawable.ic_categori3_1, R.drawable.ic_categori4_1,
				R.drawable.ic_categori5_1, R.drawable.ic_categori6_1,
				R.drawable.ic_categori7_1, R.drawable.ic_categori8_1,
				R.drawable.ic_categori9_1, R.drawable.ic_categori10_1 };

		public defaultAdapter() {
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return default_data.length;
		}

		@Override
		public String getItem(int position) {
			// TODO Auto-generated method stub
			return default_data[position];
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {

			ViewHolder v;

			if (convertView == null) {
				v = new ViewHolder();
				convertView = inflater.inflate(R.layout.search_list_default,
						null);

				v.img = (ImageView) convertView
						.findViewById(R.id.search_list_default_img);
				v.text = (TextView) convertView
						.findViewById(R.id.search_list_default_text);

				convertView.setTag(v);
			} else {
				v = (ViewHolder) convertView.getTag();
			}

			v.img.setImageResource(defalt_img[position]);
			v.text.setText(default_data[position]);

			return convertView;
		}

		class ViewHolder {
			ImageView img;
			TextView text;
		}
	}

	private class mAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return list_empty.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			return convertView;
		}
	}
}